package cc.sheji.Service;

import cc.sheji.domain.*;
import cc.sheji.reposity.*;
import cc.sheji.util.QueryHelp;
import cn.dev33.satoken.stp.StpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.persistence.criteria.Predicate;
import java.util.*;


@Service
public class PictureCollectionService {

    @Autowired
    PictureCollectionRepository pictureCollectionRepository;
    @Autowired
    LoveRepository loveRepository;
    @Autowired
    UserFocusRepository focusRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    MyPhotoRepository myPhotoRepository;


    public PictureCollection create(PictureCollection entity) {
        entity.setId(null);
        entity.setLoveNum(0);
        entity.setUserId(StpUtil.getLoginIdAsLong());
        entity = pictureCollectionRepository.save(entity);
        User user = userRepository.findById(StpUtil.getLoginIdAsLong()).get();
        List<String> formatRecentPhoto = user.getFormatRecentPhoto();
        formatRecentPhoto.addAll(entity.getFormatImages().toJavaList(String.class));
        if (formatRecentPhoto.size()>3){
            formatRecentPhoto=formatRecentPhoto.subList(0,3);
        }
        user.setFormatRecentPhoto(formatRecentPhoto);
        Integer productNum = user.getProductNum();
        if(productNum==null)
            productNum=0;
        user.setProductNum(productNum+1);
        userRepository.save(user);
        return entity;
    }

    public PictureCollection adminCreate(PictureCollection entity) {
        entity.setId(null);
        entity.setLoveNum(0);
        entity.setUserId(767L);
        String content = entity.getContent();

        StringBuilder builder=new StringBuilder();

        Document parse = Jsoup.parse(entity.getContent());
        Element body = parse.body();
        System.out.println(body.children());
        Elements children = body.children();
        for(Element element: children){
            System.out.println(element);
            String text = element.text();
            if(text!=null||!text.isEmpty()){
                builder.append("<div>");
                builder.append(element.text());
                builder.append("</div>");
            }
            Elements img = element.getElementsByTag("img");
            for (Element element1: img){
                String src2=element1.attr("src");
                System.out.println(src2);
                builder.append("<div>");
                builder.append("<img style='width:100%' src='");
                builder.append(src2);
                builder.append("' />");
                builder.append("</div>");
            }

        }
        entity.setContent(builder.toString());

        entity = pictureCollectionRepository.save(entity);
        User user = userRepository.findById(767L).get();
        Integer productNum = user.getProductNum();
        if(productNum==null)
            productNum=0;
        user.setProductNum(productNum+1);
        userRepository.save(user);
        return entity;
    }

    public PictureCollection get(@PathVariable("id") Long id) {
        PictureCollection entity = pictureCollectionRepository.findById(id).get();

        long loginId = 0L;
        try {
            loginId = StpUtil.getLoginIdAsLong();
        }catch (Exception e){
            e.printStackTrace();
        }


        if(loginId>0){
            UserFocus userFocus = focusRepository.findFirstByFocusUserIdAndUserId(StpUtil.getLoginIdAsLong(), entity.userId);

            if(userFocus!=null){
                User user = entity.getUser();
                user.setFocused(true);
                entity.setUser(user);
            }
            List<Love> loveList = loveRepository.findAll((root, query, cb) -> {
                List<Predicate> predicates = new ArrayList<>();
                //equal 示例
                predicates.add(cb.equal(root.get("userId"), StpUtil.getLoginIdAsLong()));
                predicates.add(cb.equal(root.get("pictureCollectionId"), entity.getId()));
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            });

            if(loveList.size()>0)
                entity.setLoved(true);
        }

        entity.setMyPhoto(myPhotoRepository.getList(entity.getId()));
        return entity;
    }

    public PictureCollection update(PictureCollection entity) {

        StringBuilder builder=new StringBuilder();

        Document parse = Jsoup.parse(entity.getContent());
        Element body = parse.body();
        System.out.println(body.children());
        Elements children = body.children();
        for(Element element: children){
            System.out.println(element);
            String text = element.text();
            if(text!=null||!text.isEmpty()){
                builder.append("<div>");
                builder.append(element.text());
                builder.append("</div>");
            }
            Elements img = element.getElementsByTag("img");
            for (Element element1: img){
                String src2=element1.attr("src");
                System.out.println(src2);
                builder.append("<div>");
                builder.append("<img style='width:100%' src='");
                builder.append(src2);
                builder.append("' />");
                builder.append("</div>");
            }

        }
        entity.setContent(builder.toString());
        return pictureCollectionRepository.save(entity);
    }

    public List<PictureCollection> list(PictureCollectionCriteria criteria, Pageable pageable) {




        Sort order = Sort.by(Sort.Direction.ASC, "createTime");
        if (criteria.getOrderType() != null && 2 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.DESC, "createTime");
        }
        if (criteria.getOrderType() != null && 3 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.DESC, "loveNum");
        }
        if (criteria.getOrderType() != null && 4 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.DESC, "commentNum");
        }
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);
        Page<PictureCollection> page = pictureCollectionRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<PictureCollection> content = page.getContent();

        if(criteria.getQueryType()==null){
            criteria.setQueryType(1);
        }
        long loginId = 0L;
        try {
            loginId = StpUtil.getLoginIdAsLong();
        }catch (Exception e){
            e.printStackTrace();
        }
        HashMap<Long ,Love> map=new HashMap<>();
        if( criteria.queryType == 2 &&loginId>0){
            UserFocusQueryCriteria criteria1=new UserFocusQueryCriteria();
            criteria1.setUserId(loginId);
            pageable = PageRequest.of(pageable.getPageNumber(), 100000);
            Page<Love> page1 = loveRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                    QueryHelp.getPredicate(root, criteria1, criteriaBuilder), pageable);
            for (Love love : page1.getContent()) {
                map.put(love.getPictureCollectionId(),love);
            }
        }

        for(PictureCollection pictureCollection:content){
            Long id = pictureCollection.getId();
            if(map.containsKey(id)){
                pictureCollection.setLoved(true);
            }else{
                pictureCollection.setLoved(false);
            }
            pictureCollection.setMyPhoto(myPhotoRepository.getList(pictureCollection.getId()));
        }

        return content;
    }


    public List<PictureCollection> mineList(PictureCollectionCriteria criteria, Pageable pageable) {

        Sort order = Sort.by(Sort.Direction.ASC, "createTime");
        if (criteria.getOrderType() != null && 2 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.DESC, "createTime");
        }
        if (criteria.getOrderType() != null && 3 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.DESC, "loveNum");
        }
        if (criteria.getOrderType() != null && 4 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.DESC, "commentNum");
        }
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);

        Page<PictureCollection> page = pictureCollectionRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);

        List<Love> loveList = loveRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            //equal 示例
            predicates.add(cb.equal(root.get("userId"), StpUtil.getLoginIdAsLong()));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        });
        System.out.println("lovelist:"+loveList);
        List<PictureCollection> content = page.getContent();
        Map<Long ,Love> loveMap=new HashMap<>();
        for(int i=0;i<loveList.size();i++){
            Love love = loveList.get(i);
            loveMap.put( love.getPictureCollectionId(),love);
        }
        for(PictureCollection item :content){
            boolean b = loveMap.containsKey(item.getId());
            item.setLoved(b);
            item.setMyPhoto(myPhotoRepository.getList(item.getId()));
        }
        return content;
    }

    public boolean delete(@PathVariable("id") Long id) {

        PictureCollection entity = pictureCollectionRepository.findById(id).get();
        entity.setDeleted(1);
        pictureCollectionRepository.save(entity);
        return true;
    }


    public boolean update(Long id, ArrayList<MyPhoto> ids) {
        System.out.println(id);
        System.out.println(ids);

        List<Long> ids1=new ArrayList<>();
        for(MyPhoto myPhoto:ids)
            ids1.add(myPhoto.getId());
       myPhotoRepository.updateParentId(id,ids1);
        return true;
    }

    public long total() {
       return pictureCollectionRepository.count();
    }
}
